package secondFragment.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

import com.example.xuegengwang.xuegengwang.R;
import com.google.gson.Gson;

import org.xutils.ex.DbException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import common.BaseFragment;
import common.Constant;
import https.InterNetController;
import https.handler.ErrorPageHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import secondFragment.adapter.OAExpandableLvAdapter;
import secondFragment.bean.OnlineAskBean;
import secondFragment.bean.VolunteerListBean;
import utils.FileUtils;
import view.MyPtrRefresh_LoadView;
import view.MyToFourFragmentDialog;

/**
 * Created by Administrator on 2017/2/18.
 * 志愿者列表
 */
@SuppressLint("ValidFragment")
public class OnlineAskFragment extends BaseFragment {
    private View view;
    private ExpandableListView online_ask_expandablelv;
    private OAExpandableLvAdapter adapter;
    private ArrayList<OnlineAskBean.CollegeListBean> parentList = new ArrayList<>();//志愿者组数据
    private Map<String, List<VolunteerListBean.ConsulterListBean>> dataSet = new HashMap<>();//志愿者全部数据
    private final int GET_VOLUNTEER_GROUP = 0;
    private final int GET_VOLUNTEER_LIST = 1;
    private MyPtrRefresh_LoadView online_ask_ptrRefresh_loadView;


    private ErrorPageHandler myHandler = new ErrorPageHandler(true) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS:
                    switch (msg.arg1) {
                        case GET_VOLUNTEER_GROUP://获取志愿者组列成功
                            String json = (String) msg.obj;
                            Gson gson = new Gson();
                            OnlineAskBean onlineAskBean = gson.fromJson(json, OnlineAskBean.class);
                            if (onlineAskBean != null) {
                                if ("1".equals(onlineAskBean.getShowcompinfo())) {
                                    //需要显示选择地区
                                    MyToFourFragmentDialog dialog = new MyToFourFragmentDialog(getMyActivity(), R.style.confirmDialog);
                                    dialog.show();
                                }
                                ArrayList<OnlineAskBean.CollegeListBean> parentList1 = (ArrayList<OnlineAskBean.CollegeListBean>) onlineAskBean.getCollegeList();
                                if (parentList1 != null) {
                                    parentList.clear();
                                    for (int i = 0; i < parentList1.size(); i++) {
                                        parentList.add(parentList1.get(i));
                                    }
                                }
                                changeGroupData(parentList);
                                adapter.notifyDataSetChanged();
                                online_ask_ptrRefresh_loadView.OnRefreshComplete();
                                for (int i = 0; i < parentList.size(); i++) {
                                    online_ask_expandablelv.collapseGroup(i);
                                }
                            }
                            break;
                        case GET_VOLUNTEER_LIST://获取志愿者列表成功
                            String json1 = (String) msg.obj;
                            Gson gson1 = new Gson();
                            VolunteerListBean volunteerListBean = gson1.fromJson(json1, VolunteerListBean.class);
                            if (volunteerListBean.getConsulterList() != null) {

                                if (volunteerListBean.getConsulterList().size() > 0) {
                                    try {
                                        FileUtils.getInstance().saveVolunteers(volunteerListBean, volunteerListBean.getConsulterList().get(0).getCollege());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    try {
                                        VolunteerListBean volunteers = FileUtils.getInstance().getVolunteers(volunteerListBean.getConsulterList().get(0).getCollege());
                                        List<VolunteerListBean.ConsulterListBean> consulterList = volunteers.getConsulterList();
                                        if (consulterList != null) {
                                            if (consulterList.size() > 0) {
                                                dataSet.put(volunteerListBean.getConsulterList().get(0).getCollege(), consulterList);
                                            }
                                        }
                                    } catch (DbException e) {
                                        e.printStackTrace();
                                    } catch (ClassNotFoundException e) {
                                        e.printStackTrace();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            adapter.notifyDataSetChanged();
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getMyActivity() != null) {
            view = inflater.inflate(R.layout.online_ask_fragment, container, false);
            initView();
        }
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            //相当于Fragment的onResume
            if (getMyActivity() != null) {
                reSetData();
            }
        }
    }

    public void reSetData() {
        if (getMyActivity() != null) {
            getVolunteerGroupFromInternet();
        }
    }

    private void initView() {
        online_ask_expandablelv = (ExpandableListView) view.findViewById(R.id.online_ask_expandablelv);
        online_ask_ptrRefresh_loadView = (MyPtrRefresh_LoadView) view.findViewById(R.id.online_ask_ptrRefresh_loadView);
        online_ask_ptrRefresh_loadView.ChangeMode(true, false);
        online_ask_ptrRefresh_loadView.setMyPtrHandler(new MyPtrRefresh_LoadView.MyPtrHandler() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getVolunteerGroupFromInternet();
            }
        });
        adapter = new OAExpandableLvAdapter(getMyActivity(), dataSet, parentList);
        online_ask_expandablelv.setAdapter(adapter);
        online_ask_expandablelv.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                if(!online_ask_expandablelv.isGroupExpanded(groupPosition)){
                    //手动点开
                    try {
//                    ArrayList<ConsulterModel> volunteerList = getVolunteerFromDB(parentList.get(groupPosition).getSchool_name());//本地获取志愿者列表
                        VolunteerListBean volunteers = FileUtils.getInstance().getVolunteers(parentList.get(groupPosition).getSchool_name());
                        if (volunteers != null) {
                            ArrayList<VolunteerListBean.ConsulterListBean> volunteerList1 = (ArrayList<VolunteerListBean.ConsulterListBean>) volunteers.getConsulterList();//本地获取志愿者列表
                            if (volunteerList1.size() != parentList.get(groupPosition).getCount()) {
                                //当数据库志愿者数量与网络返回对应高校志愿者数量不同时，请求网络更新数据库志愿者数据
                                getVolunteerFromInternet(parentList.get(groupPosition).getSchool_name());//网络获取志愿者列表
                            } else {
                                //当数量一样是，直接展示本地数据库数据
                                dataSet.put(parentList.get(groupPosition).getSchool_name(), volunteerList1);
                                adapter.notifyDataSetChanged();
                            }
                        } else {
                            //当数据库里面没数据时
                            if (parentList.get(groupPosition).getCount() != 0) {
                                getVolunteerFromInternet(parentList.get(groupPosition).getSchool_name());//网络获取志愿者列表
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });
    }

    //填充志愿者组数据
    private void changeGroupData(ArrayList<OnlineAskBean.CollegeListBean> arrayList) {
        for (int i = 0; i < arrayList.size(); i++) {
            dataSet.put(arrayList.get(i).getSchool_name(), null);
        }
    }

    //获取志愿者组数据
    private void getVolunteerGroupFromInternet() {
        new InterNetController(getMyActivity(), Constant.COLLEGELIST, myHandler, null, GET_VOLUNTEER_GROUP, false);
    }

    //获取志愿者列表数据
    private void getVolunteerFromInternet(String collegeName) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("college", collegeName);
        new InterNetController(getMyActivity(), Constant.VOLUNTEER_LIST, myHandler, hashMap, GET_VOLUNTEER_LIST);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
